package com.yyk.yykywd.ui.work;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;

import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;

import com.google.gson.Gson;
import com.maning.mndialoglibrary.MProgressDialog;
import com.maning.mndialoglibrary.config.MDialogConfig;
import com.maning.mndialoglibrary.listeners.OnDialogDismissListener;
import com.orhanobut.hawk.Hawk;
import com.orhanobut.logger.Logger;
import com.yyk.yykywd.R;
import com.yyk.yykywd.adapter.MoreGridViewAdapter2;
import com.yyk.yykywd.adapter.MoreGvBean;
import com.yyk.yykywd.base.BaseActivity;
import com.yyk.yykywd.config.Constant;
import com.yyk.yykywd.config.HttpUrl;
import com.yyk.yykywd.http.ApiService;
import com.yyk.yykywd.bean.WorkBusinessapplyInfo;
import com.yyk.yykywd.bean.WorkResetvisitInfo;
import com.yyk.yykywd.listenter.DialogSureCancelListenter;
import com.yyk.yykywd.listenter.TakePhotoListenter;
import com.yyk.yykywd.listenter.ToolbarListenter;
import com.yyk.yykywd.util.DialogUtil;
import com.yyk.yykywd.util.Md5Util2;
import com.yyk.yykywd.util.OnClickFlagUtil;
import com.yyk.yykywd.util.ToastUtil;
import com.yyk.yykywd.util.UploadUtil;
import com.yyk.yykywd.widght.CustomGridView;


import org.devio.takephoto.app.TakePhoto;
import org.devio.takephoto.app.TakePhotoImpl;
import org.devio.takephoto.compress.CompressConfig;
import org.devio.takephoto.model.InvokeParam;
import org.devio.takephoto.model.TContextWrap;
import org.devio.takephoto.model.TResult;
import org.devio.takephoto.permission.InvokeListener;
import org.devio.takephoto.permission.PermissionManager;
import org.devio.takephoto.permission.TakePhotoInvocationHandler;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * 上传合作申请书
 */
public class CustomerCall3Activity extends BaseActivity implements TakePhoto.TakeResultListener, InvokeListener, UploadUtil.OnUploadProcessListener {


    @BindView(R.id.gridView)
    CustomGridView gridView;
    @BindView(R.id.et_remark)
    EditText etRemark;
    private String id; // 业务ID
    private List<File> fileList = new ArrayList<>();

    private List<MoreGvBean> mPicList = new ArrayList<>(); //上传的图片凭证的数据源
    private boolean backflag = false; //通过暂无意向列表跳转到暂无合作意向-----有合作意向传boolena true ,返回不用清除数据

    private MDialogConfig mDialogConfig;

    @Override
    public int getLayoutId() {
        return R.layout.activity_customer_call3;
    }

    @Override
    public void initView() {
        initToolbar();
        initPickPhoto();
        mDialogConfig = new MDialogConfig.Builder()
                //点击外部是否可以取消
                .isCanceledOnTouchOutside(false)
                //物理返回键可以取消
                .isCancelable(false)
                //全屏背景窗体的颜色
                .setBackgroundWindowColor(getResources().getColor(R.color.transparent))
                //View背景的圆角
                .setCornerRadius(20)
                //View 边框的宽度
                .setStrokeWidth(2)
                //Progress 宽度
                .setProgressWidth(3)
                //Progress 内圈颜色
                .setProgressRimColor(Color.GRAY)
                //Progress 内圈宽度
                .setProgressRimWidth(4)
                //ProgressBar 颜色
                .setProgressColor(Color.GRAY)
                //文字的大小：sp
                .setTextSize(15)
                //padding
                .setPadding(40, 10, 40, 10)
                //关闭的监听
                .setOnDialogDismissListener(new OnDialogDismissListener() {
                    @Override
                    public void onDismiss() {
                    }
                })
                .build();

    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        if (backflag) {
            finish();
        } else {
            postWorkResetvisit(true);

        }

    }

    private void initToolbar() {
        setBackArrow(new ToolbarListenter() {
            @Override
            public void onClickListenter() {
                if (backflag) {
                    finish();
                } else {
                    postWorkResetvisit(true);

                }
            }
        });
        setTitle("客户拜访");
    }


    @Override
    public void initData() {
        initGetIntent();
        initAdapter();
    }

    private void initGetIntent() {
        if (getBundle() != null) {
            id = getBundle().getString("id");
            boolean backFlag = getBundle().containsKey("backflag");
            if (backFlag) {
                backflag = getBundle().getBoolean("backflag");
            }
        }
    }

    /**
     * 清除垃圾缓存数据
     * <p>
     * 接口12：客户拜访 上传申请书 返回（whm
     *
     * @param flag
     */
    private void postWorkResetvisit(final boolean flag) {
        Map<String, String> map = new TreeMap<>();
        map.put("uid", Hawk.get("uid")+"");
        map.put("bid", id + "");
        map.put("sign", Md5Util2.createSign(map));
        ApiService.getInstance().api.postWorkResetvisit(map)
                .subscribeOn(Schedulers.io())     //调度线程
                .observeOn(AndroidSchedulers.mainThread())
                .unsubscribeOn(Schedulers.io())   //取消订阅
                .subscribe(new Observer<WorkResetvisitInfo>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(WorkResetvisitInfo info) {
                        Logger.e("清除数据" + info.toString());
//                        ToastUtil.showShort(info.getMsg());
                        if (info.getCode() == 1) {
                            finish();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private File file;
    private Uri uri;
    private File test;

    private void initPickPhoto() {
        //各控件初始化
        file = new File(Environment.getExternalStorageDirectory(), "/yykysd/" + System.currentTimeMillis() + ".jpg");
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        uri = Uri.fromFile(file);
    }


    MoreGridViewAdapter2 mGridViewAddImgAdapter;

    private void initAdapter() {
        //1.
        //这里写了一个回调，获取点击图片后的postion，并用HAWK 保存下来，调用删除接口 并去掉HAWK，实现完美删除法
        //        mPicList.add(new MoreGridViewItemInfo(null,"执业证",null));  本来想复用适配器中的布局，但是没成功
        mGridViewAddImgAdapter = new MoreGridViewAdapter2(mActivity, mPicList, new MoreGridViewAdapter2.DeleteItemListenter() {
            @Override
            public void onDeleteItemListenter(int postion) {
                //删除
                fileList.remove(postion);
            }
        });
        gridView.setAdapter(mGridViewAddImgAdapter);
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (position == parent.getChildCount() - 1) {
                    //如果“增加按钮形状的”图片的位置是最后一张，且添加了的图片的数量不超过3张，才能点击
                    if (mPicList.size() == Constant.MAX_SELECT_PIC_NUM2) {
                        //最多添加3张图片  暂时不做操作
                    } else {
                        showDiloag();
                    }
                } else {
                    //暂时不做操作
                }
            }
        });

    }


    /**
     * 从底部弹出 相机和相册 和取消
     */
    private void showDiloag() {
        DialogUtil.showTakePhoto(mActivity, new TakePhotoListenter() {
            @Override
            public void onCamera() {
                //拍照
                takePhoto.onPickFromCapture(uri);
                //压缩
//                CompressConfig compressConfig = new CompressConfig.Builder().setMaxSize(50 * 1024).setMaxPixel(800).create();
//                takePhoto.onEnableCompress(compressConfig, true);
            }

            @Override
            public void onPic() {
                //相册
                takePhoto.onPickFromGallery();
                //压缩
//                CompressConfig compressConfig = new CompressConfig.Builder().setMaxSize(50 * 1024).setMaxPixel(800).create();
//                takePhoto.onEnableCompress(compressConfig, true);

            }
        });

    }

    /**
     * 调用 takephoto
     */
    private TakePhoto takePhoto;
    private InvokeParam invokeParam;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        getTakePhoto().onCreate(savedInstanceState);
        super.onCreate(savedInstanceState);

    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        getTakePhoto().onSaveInstanceState(outState);
        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        getTakePhoto().onActivityResult(requestCode, resultCode, data);
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.TPermissionType type = PermissionManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.handlePermissionsResult(this, type, invokeParam, this);
    }

    /**
     * 获取TakePhoto实例
     *
     * @return
     */
    public TakePhoto getTakePhoto() {
        //获得TakePhoto实例
        if (takePhoto == null) {
            takePhoto = (TakePhoto) TakePhotoInvocationHandler.of(this).bind(new TakePhotoImpl(this, this));
        }
        //设置压缩规则，最大500kb
        takePhoto.onEnableCompress(new CompressConfig.Builder().setMaxSize(300 * 1024).setMaxPixel(800).create(), true);
        return takePhoto;
    }


    /**
     * 获取到 相机路径
     *
     * @param result
     */
    @Override
    public void takeSuccess(TResult result) {
        Logger.i("takeSuccess：" + result.getImage().getOriginalPath());
        Logger.i("takeSuccess：" + result.getImage().getCompressPath());
        Logger.i("takeSuccess：" + result.getImage().getFromType());
        //成功取得照片
        test = new File(result.getImage().getOriginalPath());
        //TODO 以后会遇到图片验证的问题
        fileList.add(test);
        mPicList.add(new MoreGvBean(test.toString(), "", ""));
        mGridViewAddImgAdapter.notifyDataSetChanged();

    }


    @Override
    public void takeFail(TResult result, String msg) {
        Logger.i("takeFail:" + msg);
    }

    @Override
    public void takeCancel() {
        Logger.i("操作被取消");
    }

    @Override
    public PermissionManager.TPermissionType invoke(InvokeParam invokeParam) {
        PermissionManager.TPermissionType type = PermissionManager.checkPermission(TContextWrap.of(this), invokeParam.getMethod());
        if (PermissionManager.TPermissionType.WAIT.equals(type)) {
            this.invokeParam = invokeParam;
        }
        return type;
    }

    /**
     * 调用 上传图片工具类方法 发送
     *
     * @param responseCode
     * @param message
     */
    @Override
    public void onUploadDone(int responseCode, String message) {
        Message msg = Message.obtain();
        msg.what = 1;
        msg.obj = message;
        handler.sendMessage(msg);
    }

    @Override
    public void onUploadProcess(int uploadSize) {

    }

    @Override
    public void initUpload(int fileSize) {

    }

    /**
     * 主线程 更新UI
     */
    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    Logger.i("响应码：" + msg.arg1 + "\n响应信息：" + msg.obj + "\n耗时：" + UploadUtil.getRequestTime() + "秒");
                    String result = (String) msg.obj;
                    Gson gson = new Gson();
                    WorkBusinessapplyInfo info = gson.fromJson(result, WorkBusinessapplyInfo.class);
                    ToastUtil.showShort(info.getMsg());
                    if (info.getCode() == 1) {
//                        if (intentflag.equals("0")) {
//                            finish();
//                        } else {
                        //关闭客户拜访 界面，跳转到待签合同
                        if (CustomerCallActivity.intance != null) {
                            CustomerCallActivity.intance.finish();
                        }
                        if (CustomerCall2Activity.intance != null) {
                            CustomerCall2Activity.intance.finish();
                        }
                        if (NoHezuoActivity.intance != null) {
                            NoHezuoActivity.intance.finish();
                        }
                        Bundle bundle = new Bundle();
                        bundle.putString("id", id + "");
                        bundle.putString("intentflag", "10");
                        startAct(QuerySignedctActivity.class, true, bundle);
//                        }
                    }else{
                        MProgressDialog.dismissProgress();
                    }


            }
            super.handleMessage(msg);
        }

    };


    @OnClick(R.id.bt_save)
    public void onViewClicked() {
        if (OnClickFlagUtil.isFastClick()) {
            return;
        }
        if (fileList.size() == 0 | fileList == null) {
            ToastUtil.showShort("请上传合作申请书照片");
            return;
        }
        final UploadUtil uploadUtil = new UploadUtil();
        uploadUtil.setOnUploadProcessListener(this);  //设置监听器监听上传状态
        DialogUtil.showReturnTips(mActivity, "", "保存后，可在“待签合同”模块中，跟进此业务"
                , "确定", "取消", new DialogSureCancelListenter() {
                    @Override
                    public void onSureListenter() {
                        MProgressDialog.showProgress(mActivity,"数据上传中...",mDialogConfig);

                        Map<String, String> map = new TreeMap<>();
                        map.put("uid", (Hawk.get("uid") + ""));
                        map.put("bid", (id + ""));
                        map.put("remark", etRemark.getText().toString().trim());
                        map.put("sign", Md5Util2.createSign(map));
                        uploadUtil.uploadFileMore(fileList, "file[]", HttpUrl.BASE_URL + "business/work/business_apply", map);

                    }

                    @Override
                    public void onCancelListenter() {

                    }
                }, false);


    }
}
